package servlet;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tool.DataFileHandler;

@SuppressWarnings("serial")
public class PageBuilder extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		
		String realPath = request.getSession().getServletContext().getRealPath("");
		String dataFolder = realPath + DataFileHandler.DATA_FOLDER;
		
		File origin = new File(dataFolder + DataFileHandler.DATA_ORIGIN);
		String[] names = origin.list(new FilenameFilter(){

			public boolean accept(File dir, String name) {
				if (new File(dir, name).isDirectory()) {
					return false;
				} else {
					return true;
				}
			}
			
		});
		
		if(names.length == 0){
			request.getSession().setAttribute("message", "There is no configuration file!");
			response.sendRedirect("error.jsp");
			return;
		}
		
		String append = names[0];
		for(int i = 1; i < names.length; i++){
			append += "|" + names[i];
		}
		
		request.getSession().setAttribute("option", append);
		
		request.getRequestDispatcher("upload.jsp").forward(request,response);
	}

}
